package com.cooper.service.trade;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cooper.dao.trade.OrderAddressDAO;
import com.cooper.dao.trade.OrderInfoDAO;
import com.cooper.dao.trade.OrderItemDAO;
import com.cooper.domain.OrderEntry;
import com.cooper.entity.OrderInfo;
import com.cooper.entity.OrderItem;
import com.cooper.pagination.PageInfo;
import com.cooper.vo.OrderSearchVo;

@Service
public class OrderRepository {
	
	@Autowired
	private OrderInfoDAO orderInfoDao;
	
	@Autowired
	private OrderItemDAO orderItemDao;
	
	@Autowired
	private OrderAddressDAO orderAddressDao;
	
	public Long addOrder(OrderEntry entry) throws Exception{
		entry.setOrderNumber();
		Long id = this.orderInfoDao.addOrderInfo(entry.getOrderInfo());
		this.orderAddressDao.addAddress(entry.getOrderAddress());
		for(OrderItem orderItem: entry.getOrderItems()){
			this.orderItemDao.addOrderItem(orderItem);
		}
		return id;
	}
	
	public OrderInfo getOrderInfo(String orderNum) throws Exception{
		return this.orderInfoDao.getOrderInfo(orderNum);
	}
	
	public int queryOrderInfoCount(OrderSearchVo searchVo){
		Long userId = searchVo.getUserId();
		if(null == userId || 0 == userId){
			return this.orderInfoDao.queryOrderInfoCountForSeller(searchVo);
		} else {
			return this.orderInfoDao.queryOrderInfoCountForBuyer(searchVo);
		}
	}
	
	public List<String> queryOrderNumList(OrderSearchVo searchVo, PageInfo pageInfo){
		Long userId = searchVo.getUserId();
		if(null == userId || 0 == userId){
			return this.orderInfoDao.queryOrderNumListForSeller(searchVo, pageInfo);
		} else {
			return this.orderInfoDao.queryOrderNumListForBuyer(searchVo, pageInfo);
		}
	}
	
	public OrderEntry getOrderEntry(String orderNum) throws Exception{
		OrderEntry entry = new OrderEntry();
		OrderInfo orderInfo = this.orderInfoDao.getOrderInfo(orderNum);
		if(null == orderInfo){
			return null;
		}
		entry.setOrderNum(orderNum);
		entry.setOrderInfo(orderInfo);
		entry.setOrderAddress(this.orderAddressDao.getAddress(orderNum));
		entry.setOrderItems(this.orderItemDao.getOrderItemListByOrderNumber(orderNum));
		entry.setOrderNumber();
		return entry;
	}
	
}
